package com.qilin.hammer.util;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.restlet.data.Form;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import com.vitria.m3oui.security.XXTEA;

public class BaseRestService extends junit.framework.TestCase{
    
    private static final Log log_ = LogFactory.getLog(BaseRestService.class);
    
    public static String M3OUI_PREFIX ="http://10.111.5.109:8080/m3oui"; //"http://localhost:8080/m3oui";
    
    public static String LOGIN_URL = M3OUI_PREFIX + "/rest/login";
    public static String LOGOUT_URL = M3OUI_PREFIX + "/rest/logout";
    public static String URL_PREFIX = M3OUI_PREFIX + "/rest";
    
    private static String TOKEN_NAME = "vttoken";
    
    private String token_ = null;
    
    public BaseRestService(String name) {
        super(name);
    }
    
    @BeforeClass 
    protected void setUp() throws Exception {
        ClientResource resource = new ClientResource(LOGIN_URL);
        try {
            Form form = new Form();
            form.add("username", "vtbaadmin");
            form.add("password", XXTEA.encryptM3OData("vitria", ""));
            Representation rep = resource.post(form.getWebRepresentation());
            token_ = rep.getText();
            System.out.println(token_);
        } catch(Exception e) {
            log_.error(e.getMessage(), e);
            assertEquals("Fail to login", true, false);
        }
    }
    
    @AfterClass
    protected void tearDown() throws Exception {
        ClientResource resource = new ClientResource(LOGOUT_URL);
        attachToken(resource);
        resource.get();
    }
    
    /*protected void setHeader(ClientResource resource, String key, String value) {
        HttpRequest request = (HttpRequest)resource.getRequest();
        request.getHttpCall().getRequestHeaders().set(key, value);
    }*/
    
    public ClientResource createSecureClientResource(String url) {
        int pos = url.indexOf("?");
        if(pos != -1) {
            url += "&" + TOKEN_NAME + "=" + token_;
        } else {
            url += "?" + TOKEN_NAME + "=" + token_;
        }
        return new ClientResource(url);
    }
    
    protected void attachToken(ClientResource resource) {
        resource.getRequestAttributes().put(TOKEN_NAME, token_);
        // setHeader(resource, TOKEN_NAME, token_);
    }
    
}